document.addEventListener('DOMContentLoaded', function() {
    // 获取容器元素
    const hikesContainer = document.querySelector('.hike-grid');
    const loadingIndicator = document.createElement('div');
    loadingIndicator.className = 'loading-indicator';
    loadingIndicator.innerHTML = '<div class="spinner"></div><p>加载中...</p>';
    loadingIndicator.style.display = 'none';
    document.body.appendChild(loadingIndicator);

    // 错误提示元素
    const errorMessage = document.createElement('div');
    errorMessage.className = 'error-message';
    errorMessage.style.display = 'none';
    document.body.appendChild(errorMessage);

    // 获取筛选按钮
    const allRegionBtn = document.getElementById('all-region');
    const jiangsuBtn = document.getElementById('jiangsu');
    const zhejiangBtn = document.getElementById('zhejiang');
    const shanghaiBtn = document.getElementById('shanghai');

    const allDiffBtn = document.getElementById('all_difficulty');
    const simpleDiffBtn = document.getElementById('simple_difficulty');
    const mediumDiffBtn = document.getElementById('medium_difficulty');
    const hardDiffBtn = document.getElementById('Hard_difficulty');

    // 获取搜索相关元素
    const searchInput = document.getElementById('route-search');
    const searchBtn = document.getElementById('search');

    // 当前筛选条件
    let currentFilters = {
        region: '全部地区',
        difficulty: '全部难度',
        search: ''
    };

    // 初始化筛选按钮
    function initFilterButtons() {
        // 地区按钮事件
        [allRegionBtn, jiangsuBtn, zhejiangBtn, shanghaiBtn].forEach(btn => {
            btn?.addEventListener('click', function() {
                // 更新按钮状态
                [allRegionBtn, jiangsuBtn, zhejiangBtn, shanghaiBtn].forEach(b => b?.classList.remove('active'));
                this.classList.add('active');

                // 更新筛选条件
                currentFilters.region =
                    this.id === 'jiangsu' ? '江苏省' :
                    this.id === 'zhejiang' ? '浙江省' :
                    this.id === 'shanghai' ? '上海市' : '全部地区';

                applyFilters();
            });
        });

        // 难度按钮事件
        [allDiffBtn, simpleDiffBtn, mediumDiffBtn, hardDiffBtn].forEach(btn => {
            btn?.addEventListener('click', function() {
                // 更新按钮状态
                [allDiffBtn, simpleDiffBtn, mediumDiffBtn, hardDiffBtn].forEach(b => b?.classList.remove('active'));
                this.classList.add('active');

                // 更新筛选条件
                currentFilters.difficulty =
                    this.id === 'simple_difficulty' ? '简单' :
                    this.id === 'medium_difficulty' ? '中等' :
                    this.id === 'Hard_difficulty' ? '困难' : '全部难度';

                applyFilters();
            });
        });
    }

    // 初始化搜索功能
    function initSearch() {
        if (!searchInput || !searchBtn) return;

        // 点击查询按钮触发搜索
        searchBtn.addEventListener('click', function() {
            currentFilters.search = searchInput.value.trim();
            applyFilters();
        });

        // 回车键也可以触发搜索
        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                currentFilters.search = this.value.trim();
                applyFilters();
            }
        });
    }

    // 应用筛选条件
    async function applyFilters() {
        try {
            // 显示加载状态
            loadingIndicator.style.display = 'flex';
            errorMessage.style.display = 'none';

            // 构建查询参数
            const params = new URLSearchParams();
            if (currentFilters.region !== '全部地区') params.append('region', currentFilters.region);
            if (currentFilters.difficulty !== '全部难度') params.append('difficulty', currentFilters.difficulty);
            if (currentFilters.search) params.append('search', currentFilters.search);

            // 发送请求
            const response = await fetch(`/api/hikes?${params.toString()}`);

            if (!response.ok) throw new Error(`HTTP错误! 状态码: ${response.status}`);

            const data = await response.json();
            if (!data.success) throw new Error('服务器返回不成功的响应');

            updateHikeList(data.data);
        } catch (error) {
            console.error('获取数据时出错:', error);
            errorMessage.textContent = '获取数据时出错，请稍后重试';
            errorMessage.style.display = 'block';
        } finally {
            loadingIndicator.style.display = 'none';
        }
    }

    // 更新路线列表 - 使用首页样式
    function updateHikeList(hikes) {
        if (!hikesContainer) return;

        hikesContainer.innerHTML = hikes.length ? '' : '<div class="no-results">没有找到匹配的徒步路线</div>';

        hikes.forEach(hike => {
            const hikeCard = document.createElement('div');
            hikeCard.className = 'hike-card';

            // 生成评分星星
            const stars = Array.from({length: 5}, (_, i) =>
                `<svg class="star ${i < Math.floor(hike.score || 0) ? 'filled' : ''}" xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                    <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
                </svg>`
            ).join('');

            hikeCard.innerHTML = `
                <div class="card-image">
                    <img src="${hike.image ? '/static/images/' + hike.image : '/static/images/default-hike.jpg'}"
                         alt="${hike.name || '未命名路线'}" loading="lazy">
                    <div class="image-overlay"></div>
                    <span class="difficulty-tag ${(hike.difficulty || '').toLowerCase()}">${hike.difficulty || '未知'}</span>
                    <button class="save-btn">
                        <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"></path>
                        </svg>
                    </button>
                </div>
                <div class="card-content">
                    <div class="card-header">
                        <h3 class="hike-name">${hike.name || '未命名路线'}</h3>
                        <div class="rating">
                            ${stars}
                            <span>${hike.score || '0'}</span>
                        </div>
                    </div>
                    <p class="location">
                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"></path>
                            <circle cx="12" cy="10" r="3"></circle>
                        </svg>
                        ${hike.address || '未知地区'}
                    </p>
                    <div class="card-stats">
                        <div class="stat">
                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                <path d="M3 3v18h18"></path>
                                <path d="M18.7 8l-5.1 5.2-2.8-2.7L7 14.3"></path>
                            </svg>
                            <span class="hike-length">${hike.length || '0'} km</span>
                        </div>
                        <div class="stat">
                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                <circle cx="12" cy="12" r="10"></circle>
                                <polyline points="12 6 12 12 16 14"></polyline>
                            </svg>
                            <span>${hike.duration || '0'}小时</span>
                        </div>
                        <div class="stat">
                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                <rect x="3" y="4" width="18" height="18" rx="2" ry="2"></rect>
                                <line x1="16" y1="2" x2="16" y2="6"></line>
                                <line x1="8" y1="2" x2="8" y2="6"></line>
                                <line x1="3" y1="10" x2="21" y2="10"></line>
                            </svg>
                            <span class="hike-best_time">${hike.best_time || '全年'}</span>
                        </div>
                    </div>
                    <a href="/hike/${hike.id || '#'}" class="explore-btn">
                        探索路线
                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <path d="M5 12h14"></path>
                            <path d="M12 5l7 7-7 7"></path>
                        </svg>
                    </a>
                </div>
            `;
            hikesContainer.appendChild(hikeCard);
        });
    }

    // 初始化所有功能
    initFilterButtons();
    initSearch();
    if (!document.querySelector('.hike-card')) applyFilters();
});